﻿CREATE PROCEDURE [dbo].[CreateMedia]
	@ProviderURL NVARCHAR(500),
	@MediaDesc NVARCHAR(1000), 
	@Title NVARCHAR(1000),
	@ThumbnailHeight INT,
	@ThumbnailWidth INT,
	@HTML NVARCHAR(500),
	@AuthorName NVARCHAR(255),
	@MediaVersion NVARCHAR(255),
	@ProviderName NVARCHAR(255),
	@ThumbnailURL NVARCHAR(1500),
	@MediaType NVARCHAR(255),
	@AuthorURL NVARCHAR(500)
AS
BEGIN
	BEGIN TRY
		SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
		SET NOCOUNT ON;
		DECLARE @tmp TABLE (pk BIGINT);
		DECLARE @id BIGINT;
		DECLARE @datacounter INT;
		DECLARE @report XML;

		INSERT INTO [Raw].[vwMedia]	(ProviderURL
									,MediaDesc
									,Title
									,ThumbnailHeight
									,ThumbnailWidth
									,HTML
									,AuthorName
									,MediaVersion
									,ProviderName
									,ThumbnailURL
									,MediaType
									,AuthorURL
									,CreatedBy
									,DateCreated
									,DateDeleted
									,VersionDate
									,VersionUser)

		OUTPUT Inserted.MediaID INTO @tmp
		VALUES	(@ProviderURL
				 ,@MediaDesc
				 ,@Title
				 ,@ThumbnailHeight
				 ,@ThumbnailWidth
				 ,@HTML
				 ,@AuthorName
				 ,@MediaVersion
				 ,@ProviderName
				 ,@ThumbnailURL
				 ,@MediaType
				 ,@AuthorURL
				 ,SYSTEM_USER
				 ,GETDATE()
				 ,NULL
				 ,GETDATE()
				 ,SYSTEM_USER);

		SELECT @id = pk FROM @tmp

		/***  Logging  ***/
		SELECT @datacounter = @@ROWCOUNT;
		SET @report = (SELECT	'Data Created'	AS LogMessage,
								GETDATE()		AS LogTimestamp,
								@datacounter	AS RowsAffected
								FOR XML PATH('Notification'),
								TYPE,
								ROOT('Activity'));	

		EXEC dbo.CreateLog @LogType = 'CREATE', @TableName = 'Media', @Metadata = @report;
		RETURN 0
	END TRY
	BEGIN CATCH
		DECLARE @ErrorMessage NVARCHAR(4000);
		DECLARE @ErrorSeverity INT;
		DECLARE @ErrorState INT;
		DECLARE @ErrorTimeStamp DATETIME;
		DECLARE @ErrAction NVARCHAR(25);

		SELECT	@ErrorMessage   = ERROR_MESSAGE(),
				@ErrorSeverity  = ERROR_SEVERITY(),
				@ErrorState     = ERROR_STATE(),
				@ErrorTimeStamp = GETDATE(),
				@ErrAction      = 'CREATE';

		SET @report = (SELECT	@ErrorMessage	AS ErrorMessage,
								@ErrAction	AS ErrorAction,
								@ErrorSeverity	AS ErrorSeverity,
								@ErrorState		AS ErrorState,
								@ErrorTimeStamp AS ErrorTimestamp 
								FOR XML PATH('Error'), 
								TYPE, 
								ROOT('ErrorLog'));		

		EXEC dbo.CreateErrorLog @ErrorType = 'ERROR', @ErrorAction = @ErrAction, @TableName = 'Media', @Metadata = @report;
	END CATCH
END